<?php
/**
 *   Author: Yanlongli <jobs@yanlongli.com>
 *   Date:   2019/11/16
 *   IDE:    PhpStorm
 *   Desc:
 */

namespace yanlongli\temporaryMailboxGrab;


class Curl
{

    /**
     * @param $url
     * @param string $method 'post' or 'get'
     * @param null $postData
     *      类似'para1=val1&para2=val2&...'，
     *      也可以使用一个以字段名为键值，字段数据为值的数组。
     *      如果value是一个数组，Content-Type头将会被设置成multipart/form-data
     *      从 PHP 5.2.0 开始，使用 @ 前缀传递文件时，value 必须是个数组。
     *      从 PHP 5.5.0 开始, @ 前缀已被废弃，文件可通过 \CURLFile 发送。
     * @param array $options
     * @param array $errors
     * @return mixed
     */
    public static function execute($url, $method, $postData = null, $options = array(), &$errors = array())
    {

        $header = [
            'Accept: application/json, text/javascript, */*; q=0.01',
//            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: zh-CN,zh;q=0.9',
            'Connection: keep-alive',
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
//            'Cookie: PHPSESSID=340abf1a618653fef13589101044e994; ZDEDebuggerPresent=php,phtml,php3; CNZZDATA1583751=cnzz_eid%3D572091052-1569547668-%26ntime%3D1569553068',
//            'Host: localhost_mlf.com',
            'Origin: ' . $url,
            'Referer: /',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
            'X-Requested-With: XMLHttpRequest',
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 150); //设置cURL允许执行的最长秒数

        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (strtolower($method) === 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postData !== null) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
        }

        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }

        if (!($output = curl_exec($ch))) {
            $errors = array(
                    'errno' => curl_errno($ch),
                    'error' => curl_error($ch),
                ) + curl_getinfo($ch);
        }

        curl_close($ch);
        return $output;
    }

    public static function get($url)
    {
        return self::execute($url, 'get');
    }

}